import { useEffect, useRef, useState } from "react";

export const isFalsy = (value: unknown) => (value === 0 ? false : !value);
export const isVoid = (value: unknown) =>
  value === undefined || value === null || value === "";

// notice：不要在一个函数中改变传入的对象
// obj如果指定为对象的话覆盖返回很广 不好
export const cleanObject = (obj: { [key: string]: unknown }) => {
  const res = { ...obj };
  Object.keys(obj).forEach((key) => {
    const value = obj[key];
    if (isVoid(value)) {
      delete res[key];
    }
  });
  return res;
};

// notice：useMount抽取出所有只加载一次的函数
export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
    // TODO 依赖项中加上callback会造成无限循环 这个和useCallback和useMemo有关系
    // eslint-disable-next-line
  }, []);
};
// ?表示可传可不传
// notice：用泛型，传入什么类型传出什么类型
export const useDebounce = <V>(value: V, delay?: number): V => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const timeout = setTimeout(() => setDebouncedValue(value), delay);
    // 每次在上一个useEffect处理完之后运行
    return () => {
      clearTimeout(timeout);
    };
  }, [value, delay]); // 当value变化的时候新设置一个定时器
  return debouncedValue;
};

export const useArray = <T>(initialArray: T[]) => {
  const [value, setValue] = useState(initialArray);
  return {
    value,
    setValue,
    add: (item: T) => {
      setValue([...value, item]);
    },
    clear: () => {
      setValue([]);
    },
    removeIndex: (index: number) => {
      const copy = [...value];
      copy.splice(index, 1);
      setValue(copy);
    },
  };
};

export const useDocumentTitle = (
  title: string,
  keepOnUnmount: boolean = true
) => {
  const oldTitle = useRef(document.title).current;
  // 页面加载时的title：oldTitle === 'JIRA'
  // 页面加载后的title：oldTitle === newTitle
  useEffect(() => {
    document.title = title;
    // title变化的时候useEffect被触发
  }, [title]);
  useEffect(() => {
    return () => {
      // 页面为刚加载时的文档标题
      if (!keepOnUnmount) {
        console.log("卸载时的oldTitle", oldTitle);
        // 页面卸载时 如果不指定依赖读到的就是旧title
        document.title = oldTitle;
      }
    };
  }, [keepOnUnmount, oldTitle]);
};

export const resetRoute = () => {
  window.location.href = window.location.origin;
};
